package za.co.johanmynhardt.jee.service;

import java.util.logging.Logger;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import za.co.johanmynhardt.jee.entity.Comment;
import za.co.johanmynhardt.jee.entity.Post;

/**
 * @author johan.mynhardt@thumbtribe.mobi
 * @version 2011.0722
 *          Time: 11:35 PM
 */
@Stateless
@Local
public class PostService {
	private Logger logger = Logger.getLogger(PostService.class.getName());
	
	@PersistenceContext
	EntityManager entityManager;

	public void savePost(Post post) {
		logger.fine("Updating post: " + post);
		entityManager.merge(post);
	}

	public void saveComment(Comment comment) {
		entityManager.merge(comment);
	}

	public Post getPostById(Long id) {
		try {
			return (Post)entityManager.createQuery("select p from Post p where p.id = :id")
					.setParameter("id", id)
					.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}
